字符串问题——判断两个字符串是否互为变形词

题目:给定两个字符串str1和str2,如果两个字符串中的字符种类一样且每种字符出现的次数一样,则称str1和str2互为变形词。请实现一个函数,判断两个字符串是否互为变形词。
例:
str1=”123”, str2=”213”, 返回true。
str1=”123”,str2=”2331”,返回false。

实现:

  1. 如果str1和str2的长度不同,则返回false。
  2. 假设字符出现的编码在0~255之间,申请长度为256的int型数组map,map[a]=b表示字符a出现了b次。
  3. 遍历字符串str1,如果遇到相应的字符,就在该位置加1。

遍历字符串str2,如果遇到相应字符就减1,如果小于0了就返回false。遍历完之后所有位置的值都为0,则返回true。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class IsDeformation {
public boolean isDeformation (String str1, String str2) {
if (str1 == null || str2 == null || str1.length() == 0 || str2.length() == 0) {
return false;
}
char[] chas1 = str1.toCharArray();
char[] chas2 = str2.toCharArray();
int[] map = new int[256];
//将str1中的字符放入map,统计相应字符的个数
for (int i = 0; i < chas1.length; i++) {
map[chas1[i]]++;
}
//如果在chas2中遇到相应的字符,则减1
for (int i = 0; i < chas2.length; i++) {
map[chas2[i]]--;
}
for (int i = 0; i < 256; i++) {
if (map[i] != 0){
return false;
}
}
return true;
}
1
2
3
4
5
6
7
8
	//Test
public static void main(String[] args) {
IsDeformation id = new IsDeformation();
String str1 = "123";
String str2 = "2331";
System.out.println(id.isDeformation(str1, str2));
}
}